<template>
  <a-input-number :min="minValue" 
    :max="maxValue" 
    :precision="option.scale" 
    :defaultValue="option.defaultValue" 
    @change="handleChange" 
    ref="number"></a-input-number>
</template>

<script>
import debounce from 'lodash/debounce'
export default {
  name: 'Number',
  props: {
    option: {
      type: Object,
      requried: false,
      default: () => {
        return {
          maxLength: 15,
          scale: 2,
          defaultValue: undefined
        };
      }
    },
    defaultHelp: {
      type: String,
      required: false,
      default: () => {
        return '';
      }
    }
  },
  computed: {
    minValue() {
      return Number('-' + this.maxNumberStr(this.option.maxLength, this.option.scale));
    },
    maxValue() {
      return Number(this.maxNumberStr(this.option.maxLength, this.option.scale));
    },
  },
  methods: {
    handleChange(value) {
      this.setValue(this, value);
    },
    setValue: debounce((self, value) => {
      let num = String(value);
      if (value > self.maxValue || value < self.minValue) {
        self.$refs.number.blur();
      } else {
        self.$emit('change', value);
      }
    }, 500),
    maxNumberStr(length, scale) {
      let maxNumberStr = '';
      while (length > 0) {
        maxNumberStr += '9';
        length--;
      }
      if (scale > 0) {
        const index = length - scale;
        return maxNumberStr.slice(0, index) + '.' + maxNumberStr.slice(index);
      }
      return maxNumberStr;
    }
  }
}
</script>

<style scoped>

</style>